package com.code.zjm.demo.activity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.code.zjm.demo.R;
import com.code.zjm.demo.entity.Book;
import com.code.zjm.demo.service.MainService;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
    private final String TAG = MainActivity.class.getSimpleName();
    private Button startServiceBt, stopServiceBt, bindServiceBt, unbindServiceBt;
    private Intent intent;
    private MainService mainService = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
        initData();
    }

    private void initData() {
        intent = new Intent(MainActivity.this, MainService.class);
        Book book = new Book("NodeJs教程", "nodeJs author", "2017");
        intent.putExtra("book", book);
    }

    public void initView() {
        startServiceBt = (Button) findViewById(R.id.startService);
        stopServiceBt = (Button) findViewById(R.id.stopService);
        bindServiceBt = (Button) findViewById(R.id.bindService);
        unbindServiceBt = (Button) findViewById(R.id.unbindService);
    }

    public void initListener() {
        startServiceBt.setOnClickListener(this);
        stopServiceBt.setOnClickListener(this);
        bindServiceBt.setOnClickListener(this);
        unbindServiceBt.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.startService:
                startService(intent);
                Log.v(TAG, "start Service");
                break;
            case R.id.stopService:
                stopService(intent);
                Log.v(TAG, "stop Service");
                break;
            case R.id.bindService:
                bindService(intent, this, BIND_AUTO_CREATE);
                Log.v(TAG, "bind Service");
                break;
            case R.id.unbindService:
                unbindService(this);
                Log.v(TAG, "unbind Service");
                break;
        }
    }

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        mainService = ((MainService.ServiceBinder) iBinder).getService();//获取服务
        Log.v(TAG, "current count is" + mainService.getCount());
        Log.v(TAG, "service connected");
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        Log.v(TAG, "service disconnected");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        Log.v(TAG, "activity out");
    }
}
